<script lang="ts">
	import { page } from '$app/state';
	import { THREAD_STATE, type ThreadInfo } from '$lib/api/proto/roadmap_qa_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import { userStore } from '$lib/stores/user.svelte';
	import { MessageCircleQuestionMark, UserRound } from 'lucide-svelte';
	import AddContentModal from './AddContentModal.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { appStore } from '$lib/stores/app.svelte';
	import moment from 'moment';
	import ShareModal from '../map/ShareModal.svelte';

	const PAGE_SIZE = 10;
	const roadmapId = page.url.searchParams.get('roadmapId') ?? '';

	let showAddModal = $state(false);
	let showShareModal = $state(false);

	let curPage = $state(0);
	let filterByNew = $state(false);
	let totalCount = $state(null as number | null);
	let threadList = $state([] as ThreadInfo[]);
	const pageCount = $derived(Math.ceil((totalCount ?? 0) / PAGE_SIZE));

	let memberCount = $state(null as number | null);

	async function loadThreadList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapQaApiClient.listThread({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				filterByNew: filterByNew,
				offset: curPage * PAGE_SIZE,
				limit: PAGE_SIZE
			}).response
		);
		totalCount = res.totalCount;
		threadList = res.threadList;
	}

	async function loadMemberCount() {
		if (
			userStore.userSession == null ||
			userStore.userInfo?.basicInfo?.userRole != USER_ROLE.USER_ROLE_COACH
		) {
			return;
		}
		const res = await callApi(
			appStore.roadmapMemberApiClient.listMember({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				offset: 0,
				limit: 1
			}).response
		);
		memberCount = res.totalCount;
	}

	function isNewThread(thread: ThreadInfo) {
		if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH) {
			return thread.updateTime > thread.answerViewTime;
		} else if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT) {
			return thread.updateTime > thread.askViewTime;
		}
		return false;
	}

	async function viewThread(threadId: string) {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapQaApiClient.viewThread({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				threadId: threadId
			}).response
		);
	}

	$effect(() => {
		loadThreadList();
	});

	$effect(() => {
		loadMemberCount();
	});
</script>

<div class="absolute right-[20px] -top-[50px] flex gap-2 items-center">
	<div role="tablist" class="tabs tabs-box bg-base-300">
		<button
			role="tab"
			class="tab {filterByNew ? '' : 'tab-active'}"
			onclick={() => (filterByNew = false)}>全部</button
		>
		<button
			role="tab"
			class="tab {filterByNew ? 'tab-active' : ''}"
			onclick={() => (filterByNew = true)}>只看新内容</button
		>
	</div>
	{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT}
		<button class="btn btn-accent" onclick={() => (showAddModal = true)}>
			<MessageCircleQuestionMark size={16} />提问
		</button>
	{/if}
</div>

<div class="h-[calc(100vh-110px)] overflow-y-auto w-full">
	{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
		{#if memberCount == 0}
			<div class="flex flex-col justify-center items-center mt-[100px] prose max-w-none">
				<h3>问答专区是教练回答学生成员问题的地方</h3>
				<p>请邀请一些成员进来</p>
				<button class="btn btn-primary" onclick={() => (showShareModal = true)}>邀请</button>
			</div>
		{:else if memberCount != null && memberCount > 0 && totalCount == 0}
			<div class="flex flex-col justify-center items-center mt-[100px] prose max-w-none">
				<h3>没有来自成员的提问</h3>
			</div>
		{/if}
	{:else if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT && totalCount == 0}
		<div class="flex flex-col justify-center items-center mt-[100px] prose max-w-none">
			<h3>您可以向教练发起提问。</h3>
			<button class="btn btn-primary" onclick={() => (showAddModal = true)}>
				<MessageCircleQuestionMark size={16} />提问
			</button>
		</div>
	{/if}
	<ul class="list rounded-box pl-[100px] pr-[100px] gap-2 pt-[10px]">
		{#each threadList as thread}
			<li
				role="none"
				class="list-row bg-base-200 cursor-pointer"
				onclick={() => {
					viewThread(thread.threadId).then(
						() =>
							(window.location.href = `/app/roadmap/qa/detail?roadmapId=${encodeURIComponent(roadmapId)}&threadId=${encodeURI(thread.threadId)}`)
					);
				}}
			>
				<div class="flex flex-col items-center">
					{#if thread.askUserLogoUri == ''}
						<UserRound size={48} />
					{:else}
						<div class="avatar">
							<div class="w-[48px] rounded-full">
								<img alt="avatar" src={thread.askUserLogoUri} />
							</div>
						</div>
					{/if}
					{thread.askUserDisplayName}
				</div>
				<div class="prose max-w-none">
					<h3>{thread.basicInfo?.name}</h3>
					<div>
						{#if isNewThread(thread)}
							<div class="badge badge-primary">有新内容</div>
						{/if}
						{#if thread.threadState == THREAD_STATE.THREAD_STATE_OPEN}
							<div class="badge badge-secondary">可回复</div>
						{:else}
							<div class="badge badge-neutral">已关闭</div>
						{/if}
					</div>
				</div>
				<div class="w-[200px]">
					<div>发布提问:{moment(Number(thread.createTime)).format('YYYY-MM-DD HH:mm:ss')}</div>
					{#if thread.updateTime - thread.createTime > 10000}
						<div>最新更新:{moment(Number(thread.updateTime)).format('YYYY-MM-DD HH:mm:ss')}</div>
					{/if}
					{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH && thread.hasAnswerViewTime}
						<div>
							上传访问:{moment(Number(thread.answerViewTime)).format('YYYY-MM-DD HH:mm:ss')}
						</div>
					{/if}
					{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT}
						<div>上传访问:{moment(Number(thread.askViewTime)).format('YYYY-MM-DD HH:mm:ss')}</div>
					{/if}
				</div>
			</li>
		{/each}
	</ul>
	{#if pageCount > 1}
		<div class="flex justify-center mt-[20px]">
			<div class="join bg-base-200">
				{#if curPage > 0}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage - 1)}
						>上一页</button
					>
				{/if}
				{#if curPage != 0}
					<button
						class="join-item btn btn-lg {curPage == 0 ? 'btn-active' : ''}"
						onclick={() => (curPage = 0)}>1</button
					>
				{/if}
				{#if pageCount > 3 && curPage > 1}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if curPage < pageCount}
					<button class="join-item btn btn-lg btn-active">{curPage + 1}</button>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage += 1)}>{curPage + 2}</button>
				{/if}
				{#if pageCount - curPage > 4}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if pageCount - curPage > 3}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 2)}
						>{pageCount - 1}</button
					>
				{/if}
				{#if pageCount - curPage > 2}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 1)}
						>{pageCount}</button
					>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage + 1)}
						>下一页</button
					>
				{/if}
			</div>
		</div>
	{/if}
</div>

<div class="absolute -left-[10000px]">
	{#if showAddModal}
		<AddContentModal
			{roadmapId}
			onCancel={() => (showAddModal = false)}
			onOk={() => {
				showAddModal = false;
				if (curPage == 0) {
					if (filterByNew) {
						filterByNew = false;
					} else {
						loadThreadList();
					}
				} else {
					filterByNew = false;

					curPage = 0;
				}
			}}
		/>
	{/if}

	{#if showShareModal}
		<ShareModal onClose={() => (showShareModal = false)} />
	{/if}
</div>
